package hqb.dev.webdeploy.flow;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import hqb.dev.webdeploy.api.DeployPrm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 更新步骤
 *
 * @author HQB--2024-04-22
 **/
@Data
@Slf4j
public abstract class FlowStep {
    /**
     * 步骤名称
     */
    private String name;
    /**
     * 步骤描述
     */
    private String desc;


    public FlowStep(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public static List<FlowStep> parse(JSONObject x, DeployPrm prm, File unzipDir) {
        JSONArray steps = x.getJSONArray("steps");
        List<FlowStep> res = new ArrayList<>();
        for (Object step : steps) {
            JSONObject y = (JSONObject) step;
            String name = y.getStr("name");
            String desc = y.getStr("desc");
            String type = y.getStr("type");
            FlowStep swi = switch (type) {
                case "stop_pid" -> new FlowStepStopPid(name, desc, prm.getPid());
                case "replace" -> new FlowStepReplace(name, desc, y, unzipDir);
                case "mysql" -> new FlowStepMysql(name, desc, y, unzipDir);
                case "command" -> new FlowStepCommand(name, desc, y);
                default -> throw new IllegalArgumentException("Unknown step type: " + type);
            };
            res.add(swi);
        }
        return res;

    }

    public abstract void execute();
}
